package com.yzt.dynamicmodule.dialog;

import static android.app.Activity.RESULT_OK;

import android.content.Intent;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONObject;
import com.yzt.p_base.utils.NetworkUtils;
import com.yzt.p_base.utils.ToastUtil;
import com.yzt.redpack.GameTransHostActivity;
import com.yzt.zhuju.R;
import com.yzt.zhuju.dialog.BottomBaseDialog;
import com.yzt.zhuju.gift.GiftBatterManager;
import com.yzt.zhuju.gift.GiftManager;
import com.yzt.zhuju.gift.GiftSelectManager;
import com.yzt.zhuju.gift.adapter.GiftItemAdapter;
import com.yzt.zhuju.network.AresSubscriber;
import com.yzt.zhuju.network.biz.BizLayer;
import com.yzt.zhuju.network.entity.gift.Gift;
import com.yzt.zhuju.network.entity.mine.wallet.WalletBean;
import com.yzt.zhuju.utils.ActivityManagerUtils;
import com.yzt.zhuju.utils.FastClickUtils;
import com.yzt.zhuju.utils.RechargeUtil;
import com.yzt.zhuju.widget.widget.ImageLoadManger;
import com.yzt.zhuju.widget.widget.RCImageView;

import java.util.ArrayList;
import java.util.List;

/**
 * 礼物弹窗
 */
public class GameGiftDialog extends BottomBaseDialog implements GiftSelectManager.GiveGiftSelectChangedObservable {

    private TextView tvDiamonds;

    private String userId;

    private String gameId;

    private GiftItemAdapter giftItemAdapter;

    private List<Gift> dataList = new ArrayList<>();

    private Gift mGift;

    private RCImageView imgAvatar;

    private TextView tv_user_name;

    @Override
    public int getLayoutRes() {
        return R.layout.dialog_game_gift;
    }

    @Override
    public void bindView(View v) {
        if (getArguments() == null) {
            return;
        }
        gameId = getArguments().getString("extra_game_id");
        initViewClick();
        initRecycle();
        iniDiamondData();
    }

    private void initViewClick() {

        imgAvatar = findViewById(R.id.img_avatar);
        tv_user_name = findViewById(R.id.tv_user_name);
        tvDiamonds = findViewById(R.id.tv_diamonds);

        // 充值
        findViewById(R.id.tv_top_up).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                RechargeUtil.toRecharge(getActivity(), false);
            }
        });

        // 发送礼物
        findViewById(R.id.tv_gift_send).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendGift();
            }
        });

        // 关闭
        findViewById(R.id.img_close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismissAllowingStateLoss();
            }
        });

        // 送给
        findViewById(R.id.ll_send_contact).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), GameTransHostActivity.class);
                intent.putExtra("extra_type", 2);
                intent.putExtra("extra_id", gameId);
                startActivityForResult(intent, 2);
            }
        });
    }

    private void initRecycle() {
        RecyclerView rvGiftList = findViewById(R.id.rv_gift_list);
        rvGiftList.setLayoutManager(new GridLayoutManager(getContext(), 4));
        giftItemAdapter = new GiftItemAdapter(getActivity(), 1);
        rvGiftList.setAdapter(giftItemAdapter);
        dataList = GiftManager.getInstance().getDiamondGiftList();
        giftItemAdapter.initData(dataList);
        GiftSelectManager.getInstance().registerGiveGiftChangedObservable(this);
    }

    /**
     * 初始化你的钻石
     */
    private void iniDiamondData() {
        BizLayer.getInstance().getMineModule().wallet(new AresSubscriber<WalletBean>() {
            @Override
            protected void onSuccess(WalletBean walletEntry) {
                tvDiamonds.setText(walletEntry.getCandyNum() + "糖币");
            }
        });
    }

    /**
     * 发送礼物
     */
    private void sendGift() {
        //发送
        if (FastClickUtils.isFastClick()) {
            return;
        }

        if (!NetworkUtils.isConnected()) {
            ToastUtil.showMessage(getString(R.string.rc_network_exception));
            return;
        }

        if (mGift == null) {
            ToastUtil.showMessage(getString(R.string.please_select_gift));
            return;
        }

        if (userId == null) {
            ToastUtil.showMessage("请选择送礼对象");
            return;
        }

        mGift.setTabId(1);
        mGift.setNum(1);
        double totalDiamond = GiftBatterManager.getInstance().getDiamondNum();
        if (totalDiamond < mGift.getWorth()) {
            FragmentActivity activity = ActivityManagerUtils.getInstance().getTopActivity();
            if (activity != null) {
                ToastUtil.showMessage(getString(R.string.money_not_enough));
                RechargeUtil.toRecharge(activity, false);
            }
            return;
        }

        JSONObject json = new JSONObject();
        json.put("giftId", mGift.getGiftId());
        json.put("scenarioType", 2);
        json.put("userId", userId);
        json.put("activityId", gameId);

        BizLayer.getInstance().getGiftModule().postSendGiftToOther(json, new AresSubscriber<Object>() {
            @Override
            protected void onSuccess(Object response) {
                ToastUtil.showMessage("赠送成功！");
//                SendGiftEvent messageExtra = new SendGiftEvent();
//                messageExtra.setGiftIcon(mGift.getGiftIcon());
//                messageExtra.setCandyCoin(mGift.getCandyCoin());
//                messageExtra.setGiftName(mGift.getGiftName());
//                messageExtra.setGiftId(mGift.getGiftId() + "");
//                messageExtra.setTargetUid(hisUid);
//                messageExtra.setType(fromSource);
//                RxBus.getDefault().post(messageExtra);
                iniDiamondData();
            }

            @Override
            protected void onError(int code, String info) {
                super.onError(code, info);
                if (code == 934) {
                    RechargeUtil.toRecharge(getActivity(), false);
                }
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        GiftSelectManager.getInstance().unRegisterGiveGiftChangedObservable(this);
    }

    @Override
    public void selectGiftData(int type, Gift gift) {
        if (gift != null) {
            int index = -1;
            for (int i = 0; i < dataList.size(); i++) {
                dataList.get(i).setChoosed(false);
                if (gift.getGiftId() == dataList.get(i).getGiftId()) {
                    index = i;
                }
            }

            if (index >= 0) {
                dataList.get(index).setChoosed(true);
            }

            giftItemAdapter.initData(dataList);

            mGift = gift;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 2 && resultCode == RESULT_OK) {
            userId = data.getStringExtra("extra_data");
            String avatar = data.getStringExtra("extra_avatar");
            ImageLoadManger.loadIv(getContext(), avatar, imgAvatar);
            String userName = data.getStringExtra("extra_user_name");
            tv_user_name.setText(userName);
            imgAvatar.setVisibility(View.VISIBLE);
            tv_user_name.setVisibility(View.VISIBLE);
        }
    }
}
